/**
* @Description: 页面通用js方法
* @updateTime shengming 2017/11/22 14:27
*/
/***************webUploader图片上传封装**********************************/
window.uploader = {};
uploader.init=function(filePickerId,$list,fileNumLimit,submitFormData,tagert){
    var thumbnailWidth = 148.5,
        thumbnailHeight = 138.5;
    // 初始化webuploader
    var upload = WebUploader.create({
        // 选完文件后是否自动上传
        auto: true,
        swf: '../../statics/plugins/webuploader/Uploader.swf',
        server: '../../common/file/upload',
        pick: {
            id: '#'+filePickerId,
            multiple: true
        },
        fileNumLimit:fileNumLimit,//最多N个
        fileSingleSizeLimit: 5 * 1024 * 1024,//5M
        formData: submitFormData,
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png',
            // extensions: 'jpg',
            // mimeTypes: 'image/jpg'
        },
        //配置生成缩略图的选项
        thumb: {
            width: 148.5,
            height: 138.5,
            // 图片质量，只有type为`image/jpeg`的时候才有效。
            quality: 70,
            // 是否允许放大，如果想要生成小图的时候不失真，此选项应该设置为false.
            allowMagnify: false,
            // 是否允许裁剪。
            crop: true,
            // 为空的话则保留原有图片格式。
            // 否则强制转换成指定的类型。
            type: "image/jpeg"
        },
    });
    // 当有文件添加进来的时候
    upload.on( 'fileQueued', function( file ) {
        $(".tempImg").hide();
        var $li = $(
                '<div id="' + file.id + '" class="file-item thumbnail">' +
                '<img>' +
                '<div class="info">' + file.name + '</div>' +
                '<div style="top: 4px;width:inherit;" class="success info">等待上传...</div></div>'+
                '</div>'
            ),
            $img = $li.find('img');

        $btns = $('<div><a class="small-btn" href="javascript:void(0)" >删除</a></div>')
            .appendTo($li);

        $btns.on('click', 'a', function() {
            var index = $(this).index(), deg;
            switch (index) {
                case 0://删除
                    uploader.removeFile(file.id,upload,tagert[filePickerId]);
                    return;
            }
        });
        $list.append( $li );
        // 创建缩略图
        upload.makeThumb( file, function( error, src ) {
            if ( error ) {
                $img.replaceWith('<span>不能预览</span>');
                return;
            }

            $img.attr( 'src', src );
        }, thumbnailWidth, thumbnailHeight );
    });

    // 文件上传成功，给item添加成功class, 用样式标记上传成功。
    upload.on( 'uploadSuccess', function( file, response) {
        var picUrl = response.rows[0].filePath;
//        // $( '#'+file.id ).addClass('upload-state-done');
        var $li = $('#'+file.id),
            $success = $li.find('div.success');

        if(!$success.length) {
            $success = $('<div style="top: 4px;width:inherit;" class="success info"></div>').appendTo($li);
        }
        // $('<input class="'+filePickerId+'" type="hidden" value="'+response.rows[0].filePath+'"/>').appendTo($li);
        tagert[filePickerId] = response.rows[0].filePath;
        $success.text('上传成功');
    });

    // 文件上传失败，显示上传出错。
    upload.on( 'uploadError', function( file ) {
        var $li = $( '#'+file.id ),
            $error = $li.find('div.error');

        // 避免重复创建
        if ( !$error.length ) {
            $error = $('<div class="error"></div>').appendTo( $li );
        }

        $error.text('上传失败');
    });

    upload.on( 'beforeFileQueued', function(data,max) {
        //回显的数量
        var oldQueuedSize =$('div[id^='+filePickerId+'_]').length;
        if(1+oldQueuedSize>fileNumLimit){
            alert("最多上传"+fileNumLimit+"张图片");
            //upload.cancelFile(data);
            //upload.removeFile(data);
            return false;
        }
    });

    // 文件上传失败，显示上传出错。
    upload.on( 'error', function( file, max ) {
        if(file=='Q_EXCEED_NUM_LIMIT'){
            alert("最多上传"+max+"张图片");
        }else if(file=='F_EXCEED_SIZE'){
            alert("图片的最大为"+uploader.formateSize(max));
        };
    });
};

//删除图片
uploader.removeFile =function(fileId,upload,target){
    if(fileId.indexOf('WU_FILE_')>-1){
        upload.removeFile(fileId);
    };
    //清空隐藏值
    $("#"+fileId+" input").each(function () {
    });
    //删除div
    $('#'+fileId).remove();
    $('<img class="tempImg" alt="无头像" style="height: 148.5px;width:138.5px;padding-top: 0px">').appendTo($('#photoList'));
    if(top.frames['layerForm'].vm.baseOldman.photo){
        top.frames['layerForm'].vm.baseOldman.photo="";
    }
    if(top.frames['layerForm'].vm.oldmanLienceFlow){
        top.frames['layerForm'].vm.oldmanLienceFlow.photo="";
    }
};

uploader.formateSize = function(f_size) {
    var fileSize = (f_size / 1024).toFixed(2);//保留2位小数点
    var suffix   = 'KB';
    if (fileSize > 1024) {
        //formate格式化大小 --单位为MB
        fileSize = (fileSize / 1024).toFixed(2);//保留2位小数点
        suffix   = 'MB';
    }
    return fileSize+suffix;
};

//图片回显
uploader.showPixBox=function($list,fileUrls,fileIdprefix){
    $list.empty();
    if(!fileUrls){
        return;
    }
    var urls = fileUrls.split(",");
    urls.forEach(function(url,index){
        url = '../../' + url;
        var $img = $(
            '<div id="' + fileIdprefix+'_'+index+ '" class="file-item thumbnail">' +
            '<img src="' + url + '" onload="javascript:window.uploader.imgResize(138.5,148.5,this)" >' +
            '<div class="info">头像</div>' +
            '<div style="top: 4px;width:inherit;" class="success info">已上传</div></div>'+
            '</div>'
        );
        // $('<input class="'+fileIdprefix+'" type="hidden" value="'+url+'">').appendTo($img);
        $('<div class="uploaderDel"><a class="small-btn uploaderDel" href="javascript:uploader.removeFile(\'' + fileIdprefix+'_'+index+ '\')" >删除</a></div>')
            .appendTo($img);
        $list.append($img);
    });
};

//封装文件格式
uploader.fileTypes = {};

uploader.fileTypes.image = {
    title: 'Images',
    // extensions: 'gif,jpg,jpeg,bmp,png',
    // mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png',
    extensions: 'jpg',
    mimeTypes: 'image/jpg'
};

// 只允许选择excel表格文件。
uploader.fileTypes.xls = {
    title : 'Applications',
        extensions : 'xls,xlsx',
        mimeTypes : 'application/xls,application/xlsx'
};

uploader.initFile=function(filePickerId,$list,fileNumLimit,submitFormData,tagert){
    // 初始化webuploader
    var upload = WebUploader.create({
        swf: '../../statics/plugins/webuploader/Uploader.swf',
        server: '../../common/file/upload',
        pick: {
            id: '#'+filePickerId,
            multiple: true
        },
        fileNumLimit:fileNumLimit,//最多N个
        fileSingleSizeLimit: 50 * 1024 * 1024 ,//50M
        formData: submitFormData,
        accept:uploader.fileTypes,
    });
    // 当有文件添加进来的时候
    upload.on( 'fileQueued', function( file ) {
        // 当有文件被添加进队列的时候
        uploader.on( 'fileQueued', function( file ) {
            $list.append( '<div id="' + file.id + '" class="item">' +
                '<h4 class="info">' + file.name + '</h4>' +
                '<p class="state">等待上传...</p>' +
                '</div>' );
        });
    });

    // 文件上传过程中创建进度条实时显示。
    uploader.on( 'uploadProgress', function( file, percentage ) {
        var $li = $( '#'+file.id ),
            $percent = $li.find('.progress .progress-bar');
        // 避免重复创建
        if ( !$percent.length ) {
            $percent = $('<div class="progress progress-striped active">' +
                '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                '</div>' +
                '</div>').appendTo( $li ).find('.progress-bar');
        }
        $li.find('p.state').text('上传中');
        $percent.css( 'width', percentage * 100 + '%' );
    });

    // 文件上传成功，给item添加成功class, 用样式标记上传成功。
    upload.on( 'uploadSuccess', function( file, response) {
    });

    // 文件上传失败，显示上传出错。
    upload.on( 'uploadError', function( file ) {
        var $li = $( '#'+file.id ),
            $error = $li.find('div.error');

        // 避免重复创建
        if ( !$error.length ) {
            $error = $('<div class="error"></div>').appendTo( $li );
        }

        $error.text('上传失败');
    });

    upload.on( 'beforeFileQueued', function(data,max) {
        //回显的数量
        var oldQueuedSize =$('div[id^='+filePickerId+'_]').length;
        if(1+oldQueuedSize>fileNumLimit){
            alert("最多上传"+fileNumLimit+"张图片");
            //upload.cancelFile(data);
            //upload.removeFile(data);
            return false;
        }
    });

    // 文件上传失败，显示上传出错。
    upload.on( 'error', function( file, max ) {
        if(file=='Q_EXCEED_NUM_LIMIT'){
            alert("最多上传"+max+"张图片");
        }else if(file=='F_EXCEED_SIZE'){
            alert("图片的最大为"+uploader.formateSize(max));
        };
    });
};

//resize图片
uploader.imgResize = function(height,width, objImg) {
    var w = objImg.width / width,
        h = objImg.height / height,
        curWidth = objImg.width,
        curHeight = objImg.height;
    objImg.height = height;
    objImg.width = curWidth / h;
    objImg.style.left = 0 - (objImg.width - width) / 2 + "px";
};
/***************webUploader图片上传封装--END**********************************/
var  AjaxUploadUtils = {};

//ajax上传-云上传
AjaxUploadUtils.cloudInit = function(options){
    var defaults = {
        targetId:'upload',
        success:function(file, r){},
        extension:/^(jpg|jpeg|png|gif)$/,
        extensionMsg:'只支持jpg、png、gif格式的图片！',
    };
    var options = $.extend(defaults,options);
    new AjaxUpload('#'+options.targetId, {
        action: '../../sys/oss/upload?token=' + token,
        name: 'file',
        autoSubmit:true,
        responseType:"json",
        onSubmit:function(file, extension){
            // if(vm.config.type == null){
            //     alert("云存储配置未配置");
            //     return false;
            // }
            if (!(extension && options.extension.test(extension.toLowerCase()))){
                alert(options.extensionMsg);
                return false;
            }
            dialogLoading(true);
        },
        onComplete : function(file, r){
            dialogLoading(false);
            if(r.code == 0){
                dialogMsg(r.msg, 'success');
                options.success(file,r);
            }else{
                alert(r.msg);
            }
        }
    });
};


//ajax上传-ppt上传
AjaxUploadUtils.pptInit = function(options){
    var defaults = {
        targetId:'upload',
        success:function(file, r){},
        data:{},
    };
    var options = $.extend(defaults,options);
    new AjaxUpload('#'+options.targetId, {
        action: '../../srblive/file/springUpload',
        name: 'file',
        autoSubmit:true,
        responseType:"json",
        data:options.data,
        onSubmit:function(file, extension){
            if (!(extension && /^(ppt|pptx)$/.test(extension.toLowerCase()))){
                alert('ppt、pptx格式的PPT文件！');
                return false;
            }
            dialogLoading(true);
        },
        onComplete : function(file, r){
            dialogLoading(false);
            if(r.code == 0){
                dialogMsg(r.msg, 'success');
                options.success(file,r);
            }else{
                alert(r.msg);
            }
        }
    });
};
